package com.lqk.fnandroid.net

import android.util.Log
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * 对 okhttp 的简单封装
 * get 和 post
 */
object OkHttpHelper {

    private const val TAG = "OkHttpHelper"

    private val okhttpClient by lazy {
        OkHttpClient.Builder()
            .addNetworkInterceptor {
                val request = it.request()
                Log.d(TAG, "Http: ${request.url}")
                return@addNetworkInterceptor it.proceed(request)
            }
            .build()
    }

    fun doGet(url: String, params: HashMap<String, Any>): String {
        val req = Request.Builder()
            .url(url)
            .get()
            .build()
        return try {
            val resp = okhttpClient
                .newCall(req)
                .execute()
            resp.body?.string() ?: ""
        } catch (e: Throwable) {
            e.printStackTrace()
            "error"
        }
    }

    fun doPost(url: String, params: HashMap<String, Any>): String {
        val reqBody =
            "{\"name\":\"lqk\"}".toRequestBody("application/json; charset=utf-8".toMediaType())
        val req = Request.Builder()
            .url(url)
            .post(reqBody)
            .build()
        return try {
            val resp = okhttpClient.newCall(req)
                .execute()
            resp.body?.string() ?: ""
        } catch (e: Throwable) {
            e.printStackTrace()
            "error"
        }
    }

}